package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.utils.CollUtil;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 统计指定时间区间内的数据额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> arrayList = new ArrayList<>();
        arrayList.add(begin);
        while (!begin.equals(end)) {
            //日期计算,计算日期后一天对应的日期
            begin = begin.plusDays(1);
            arrayList.add(begin);
        }
//        存储每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : arrayList) {
//            查询date日期对应的营业额,营业额是指状态已生成的订单金额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
//            select sum(amount) from orders where order_time>begintime and ordertime <endtime and status = 5
            HashMap hashMap = new HashMap();
            hashMap.put("begin", beginTime);
            hashMap.put("end", endTime);
            hashMap.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(hashMap);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(arrayList, ","))
                .turnoverList(StringUtils.join(turnoverList, ", "))
                .build();
    }

    /**
     * 获取指定区间的用户数据信息
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
//        存储begin到end之间的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        存储每天存放的新增的用户数量 select count(id) from user where create_time < ? and creat_time > ?
        List<Integer> newUserList = new ArrayList<>();
//        存储每天的总用户数量 select count(id) from user from create_time < ?
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map dateMap = new HashMap();
            dateMap.put("end", endTime);
            Integer totalUser = userMapper.countByMap(dateMap);
            dateMap.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(dateMap);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 统计指定时间的订单数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //        存储begin到end之间的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        存放每天的订单总数
        List<Integer> orderCountList = new ArrayList<>();
//        存放每天有效订单数
        List<Integer> vaildOrderCountList = new ArrayList<>();
//        遍历dateList集合,查询每天的有效订单数和订单总数
        for (LocalDate date : dateList) {
//            查询每天的订单总数 select count(id) from orders where order_time > ? and order_time < ?
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
//            查询每天的有效订单数 select count(id) from orders where order_time > ? and status = ?
            Integer validorderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            vaildOrderCountList.add(validorderCount);
        }
//        计算时间区间内订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
//        计算时间区间内的有效订单数
        Integer vaildOrederCount = vaildOrderCountList.stream().reduce(Integer::sum).get();
//        计算订单完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = vaildOrederCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(vaildOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(vaildOrederCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map)
                ;
    }
    /**
     * 销量排行前10
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) { // 08-01     08-03
        // 查询指定时间范围内 商品以及对应的销量数据 前十
        List<GoodsSalesDTO> salesDTOList = orderMapper.getSaleTop10(LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX));
        // 分别定义两个集合，存储商品名称列表和销量列表
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        if (CollUtil.isNotEmpty(salesDTOList)) {
            // 从查询结果中获取销量和商品名称，分别存储到对应集合中
            for (GoodsSalesDTO salesDTO : salesDTOList) {
                nameList.add(salesDTO.getName());
                numberList.add(salesDTO.getNumber());
            }
        }
        // 封装VO并返回
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList, ","));
        return salesTop10ReportVO;
    }
}
